import pymysql
from config.settings import DB_HOST, DB_USER, DB_PASSWORD, DB_NAME


class DatabaseManage():
    def __init__(self):
        self.connection = None

    def __enter__(self):
        # print('调用enter')
        self.connection = self.create_connection()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # print('调用exit')
        self.close_connection()
        return self

    def create_connection(self):
        if not self.connection or not self.connection.open:
            try:
                self.connection = pymysql.connect(
                    host=DB_HOST,
                    user=DB_USER,
                    passwd=DB_PASSWORD,
                    database=DB_NAME,
                    cursorclass=pymysql.cursors.DictCursor
                )
                print(self.connection)
            except Exception as e:
                print(f"数据库连接错误:{e}")
        return self.connection


    def fetch_query(self,query,params=None,single=False):
        result  = None
        if self.connection:
            try:
                with self.connection.cursor() as cursor:
                    cursor.execute(query,params)
                    if single:
                        result = cursor.fetchone()
                    else:
                        result = cursor.fetchall()
            except Exception as e:
                print(f"查询出错:{e}")
            return result
        else:
            print(f"没有建立数据库连接")

    def  execute_query(self,query,params=None):
       if self.connection:
           try:
               with self.connection.cursor() as cursor:
                    cursor.execute(query,params)
                    self.connection.commit()
                    return True
           except Exception as e:
                print(f"执行异常: {e}")
                self.connection.rollback()
                return None
       else:
           print(f"没有建立数据库连接")

    def close_connection(self):
        if self.connection:
            self.connection.close()

if __name__ == '__main__':
    print("---数据库连接测试---")
    with DatabaseManage() as db:
        pass
    print("***没有报错就ok~***")